package com.zty.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @Author ZTY
 * @Description Netty客户端
 * @Date 15:43 2023-12-06
 **/

public class AppClient {

    public void run(){
        // 定义线程池
        NioEventLoopGroup group = new NioEventLoopGroup();

        //  启动一个客户端，需要一个辅助类bootstrap
        Bootstrap bootstrap = new Bootstrap();
        try {
            //创建客户端
            bootstrap = bootstrap.group(group)  //要使用那个线程池处理相关的方法
                    .remoteAddress(new InetSocketAddress(8080)) //要连接哪个服务器端口
                    .channel(NioSocketChannel.class)  //  选择初始化一个什么样的channel
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new MyChannelHandler2());
                        }
                    });

            // 尝试连接服务器（上锁，同步等待）
            ChannelFuture channelFuture = null;

                channelFuture = bootstrap.connect().sync();
                // 获取channel，并且写出数据
                channelFuture.channel().writeAndFlush(Unpooled.copiedBuffer("hello0，netty".getBytes(StandardCharsets.UTF_8)));
                // 阻塞程序，等待接受消息
                channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            try {
                group.shutdownGracefully().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        new AppClient().run();
    }
}
